package com.atguigu.gmall.list.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.list.model.Goods;
import com.atguigu.gmall.list.model.SearchParam;
import com.atguigu.gmall.list.model.SearchResponseVo;
import com.atguigu.gmall.list.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author: atguigu
 * @create: 2023-01-06 15:10
 */
@RestController
@RequestMapping("/api/list")
public class ListApiController {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    private SearchService searchService;


    /**
     * 创建商品索引库
     *
     * @return
     */
    @GetMapping("inner/createIndex")
    public Result createIndex() {
        //1.基于文档实体类创建索引库
        elasticsearchRestTemplate.createIndex(Goods.class);
        //2.基于文档实体类设置映射
        elasticsearchRestTemplate.putMapping(Goods.class);
        return Result.ok();
    }


    /**
     * 测试接口，商品文档对象录入索引
     *
     * @param skuId
     * @return
     */
    @GetMapping("/inner/upperGoods/{skuId}")
    public Result upperGoods(@PathVariable("skuId") Long skuId) {
        searchService.upperGoods(skuId);
        return Result.ok();
    }


    /**
     * 测试接口，商品文档删除
     *
     * @param skuId
     * @return
     */
    @GetMapping("/inner/lowerGoods/{skuId}")
    public Result lowerGoods(@PathVariable("skuId") Long skuId) {
        searchService.lowerGoods(skuId);
        return Result.ok();
    }

    /**
     * 更新商品的热度排名分值
     *
     * @param skuId
     * @return
     */
    @GetMapping("/inner/incrHotScore/{skuId}")
    public Result incrHotScore(@PathVariable("skuId") Long skuId) {
        searchService.incrHotScore(skuId);
        return Result.ok();
    }


    /**
     * 商品检索
     *
     * @param searchParam
     * @return
     */
    @PostMapping("/inner")
    public Result search(@RequestBody SearchParam searchParam, HttpServletRequest request) {
        //String userId = request.getHeader("userId");
        String userId1 = AuthContextHolder.getUserId(request);
        String userTempId = AuthContextHolder.getUserTempId(request);
        System.out.println("临时用户ID:"+userTempId);
        System.out.println("用户ID:"+userId1);
        SearchResponseVo responseVo = searchService.search(searchParam);
        return Result.ok(responseVo);
    }
}
